class Comment < ActiveRecord::Base
  belongs_to :user

  belongs_to :commentable, :polymorphic => true, :counter_cache => true

  has_many :attachment_links, :as => :attachable
  has_many :attachments, :through => :attachment_links

  has_many :issue_changes

  validates_presence_of :commentable_id, :commentable_type
  validates_presence_of :user_id
  validates_presence_of :summary
  validates_each :attachments do |record, attr, value|
    value.each do |a|
      unless a.valid?
        # this code just adds the individual errors:
        # a.errors.each do |error_name, error_value|
        #   record.errors.add( error_name, error_value )
        # end
        if a.is_a? IssueRef
          record.errors.add( "Issue attachment", 'requries a project name and an issue number' )
        elsif a.is_a? CommentRef
          record.errors.add( "Comment attachment (\"#{a.description}\")", 'requries a comment number' )
        elsif a.is_a? Image
          record.errors.add( "Image attachment (\"#{a.description}\")", 'is missing a file' )
        elsif a.is_a? PatchFile
          record.errors.add( "Patch file attachment (\"#{a.description}\")", 'is missing a file or a revision number' )
        elsif a.is_a? GenericFile
          record.errors.add( "File attachment (\"#{a.description}\")", 'is missing a file' )
        end
      end
    end
    # remove any automatically inserted attachments errors
    record.errors.clear_on( 'attachments' )
  end

  def inspect
    "Comment( '#{summary.nil? ? '' : summary[0..30] + ' ...'}', #{attachments.size} attachments, #{issue_changes.size} changes )"
  end
end
